package com.wish.group05.common.log.service;

import com.alibaba.fastjson.JSON;
import com.wish.group05.common.core.utils.DateUtils;
import com.wish.group05.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.wish.group05.system.api.RemoteLogService;
import com.wish.group05.system.api.domain.SysOperLog;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 异步调用日志服务
 * 
 * @author wish
 */
@Slf4j
@Service
public class AsyncLogService
{
    @Autowired
    private RemoteLogService remoteLogService;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Autowired
    private RedisService redisService;

    /**
     * 保存系统日志记录
     */
    @Async
    public void saveSysLog(SysOperLog sysOperLog)
    {
        remoteLogService.saveLog(sysOperLog);
        // 发送kafka消息
        String key = UUID.randomUUID().toString();
        kafkaTemplate.send("test",key , JSON.toJSONString(sysOperLog));
        // 防止消息丢失
        Map<String, Object> map = new HashMap<>();
        map.put("message",JSON.toJSONString(sysOperLog));
        map.put("createTime", DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));
        // 存入redis防止消息丢失
        redisService.setCacheObject("message:"+key,JSON.toJSONString(map));
    }
}
